package cn.com.note.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.com.note.R;
import cn.com.note.model.VersionModel;
import cn.com.note.service.UpdateIntentService;
import cn.com.note.service.UpdateService;
import cn.com.note.utils.DownloadDialog;

import static cn.com.note.service.UpdateIntentService.UPDATE_APK_NAME;
import static cn.com.note.service.UpdateIntentService.UPDATE_APK_URL;

/**
 * Created by sunfulin on 2019/6/24.
 */

public class VersionUpdate extends AppCompatActivity {
    private static final String TAG = VersionUpdate.class.getSimpleName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_version_update);
        findViewById(R.id.bt_update).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //版本更新
                showVersionUpdate();
            }
        });
        findViewById(R.id.bt_update2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //版本更新
                bnClick(v);
            }
        });
        findViewById(R.id.bt_update3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下载文件 判断 版本更新
                String verFile = getApplicationContext().getFilesDir().getAbsolutePath() + "/ver.txt";
                Log.d(TAG, verFile);
                downFileVersionUpdate("http://www.nxtest.yesno.com.cn/apitest/PDA_UPDATE/VER.txt", verFile);
            }
        });
        findViewById(R.id.bt_analysisFile).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下载文件 判断 版本更新
                String verFile = getApplicationContext().getFilesDir().getAbsolutePath() + "/ver.txt";
                if (FileUtils.isFile(verFile)) {
                    String verString = FileIOUtils.readFile2String(verFile);
                    Log.d(TAG, verString);
                    VersionModel versionModel = GsonUtils.fromJson(verString, VersionModel.class);
                    VersionModel.DataBean bean = versionModel.getData().get(0);
                    if (bean != null) {
                        toIntentServiceUpdate1("app_release" + bean.getVER(), bean.getDOWNLOADURL());
                    }
                }
            }
        });
        findViewById(R.id.bt_filePath).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //路径：(data/data/应用包名/files)
                Log.e(TAG, getApplicationContext().getFilesDir().getAbsolutePath());
                //应用程序的缓存目录 路径：(data/data/应用包名/cache),不过经实际测试(华为、小米手机等)，getCacheDir的手机路径为: /data//data/user/0/应用包名/cache
                Log.e(TAG, getApplicationContext().getCacheDir().getAbsolutePath());
                //SD卡的根目录，路径：/storage/emulated/0
                Log.e(TAG, Environment.getExternalStorageDirectory().getAbsolutePath());
                //路径：/storage/emulated/0/Android/data/应用包名/cache
                Log.e(TAG, "ExternalCacheDir:" + getApplicationContext().getExternalCacheDir().getAbsolutePath());
                //私有文件 路径：/storage/emulated/0/Android/data/应用包名/files
                Log.e(TAG, getApplicationContext().getExternalFilesDir("").getAbsolutePath());
                //downFileVersionUpdate();
            }
        });
        initOther();
        //参考：   https://github.com/HoldMyOwn/Update
    }


    @Override
    protected void onDestroy() {
        if (downloadDialog != null) {
            downloadDialog.unReceiver(this);
        }
        super.onDestroy();
    }

    /////////////////////////////////////////////// 第一种 进度在app内 下载完成直接安装
    private void toIntentServiceUpdate(String url, String appName) {
        Intent updateIntent = new Intent(this, UpdateIntentService.class);
        updateIntent.setAction(UpdateIntentService.ACTION_UPDATE);
        updateIntent.putExtra(UPDATE_APK_NAME, "update-1.0.1");
        updateIntent.putExtra(UPDATE_APK_URL, "http://gdown.baidu.com/data/wisegame/38cbb321c273886e/YY_30086.apk");
        startService(updateIntent);
    }

    DownloadDialog downloadDialog;

    private void initOther() {
        if (downloadDialog == null) {
            downloadDialog = new DownloadDialog(this);
            downloadDialog.setDLClickListener(new DownloadDialog.DLClickListener() {
                @Override
                public void onStart() {
                    toIntentServiceUpdate("", "");

                }

                @Override
                public void onFinish() {
                }

                @Override
                public void onCancel() {
                    //点击了取消
                    downloadDialog.stateRest();
                }
            });
        }
    }

    private void showVersionUpdate() {
        if (downloadDialog != null) {
            downloadDialog.show();
        }
    }

    /////////////////////////////////////////////// 第二种 以通知栏的方式显示


    String appName1 = "update-1.0.1";
    String appUrl1 = "http://gdown.baidu.com/data/wisegame/38cbb321c273886e/YY_30086.apk";

    public void bnClick(View view) {
        AlertDialog.Builder dialog =
                new AlertDialog.Builder(VersionUpdate.this);
        dialog.setTitle("版本更新");
        dialog.setMessage("更新至新的版本");
        dialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        beforeUpdateWork();
                    }
                });
        dialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        dialog.show();
    }

    private void beforeUpdateWork() {
        if (!isEnableNotification()) {
            showNotificationAsk();
            return;
        }
        toIntentServiceUpdate1(appName1, appUrl1);

    }

    private void showNotificationAsk() {
        AlertDialog.Builder dialog =
                new AlertDialog.Builder(VersionUpdate.this);
        dialog.setTitle("通知权限");
        dialog.setMessage("打开通知权限");
        dialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toSetting();
                    }
                });
        dialog.setNeutralButton("跳过", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                toIntentServiceUpdate1(appName1, appUrl1);
            }
        });
        dialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        dialog.show();
    }

    private boolean isEnableNotification() {
        boolean ret = true;
        try {
            NotificationManagerCompat manager = NotificationManagerCompat.from(this);
            ret = manager.areNotificationsEnabled();
        } catch (Exception e) {
            return true;
        }
        return ret;
    }

    private void toSetting() {
        try {
            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
            startActivity(localIntent);
        } catch (Exception e) {

        }
    }

    private void toIntentServiceUpdate1(String appName, String appUrl) {
        Intent update = new Intent(this, UpdateService.class);
        update.setAction(UpdateService.ACTION_UPDATE);
        update.putExtra("appName", appName);
        //随便一个apk的url进行模拟
        update.putExtra("downUrl", appUrl);
        startService(update);
    }
    /////////////////////////////////////////////////////////////////// 下载文件

    //下载文件保存到对应的目录
    private void downFileVersionUpdate(final String urlpath, final String filePath) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                com.blankj.utilcode.util.FileUtils.deleteFile(filePath);
                File file = new File(filePath);
                try {
                    URL url = new URL(urlpath);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(10000);
                    conn.setRequestProperty("Accept-Encoding", "identity");
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream inputStream = conn.getInputStream();
                    FileOutputStream fos = new FileOutputStream(file, true);
                    int oldProgress = 0;
                    byte buf[] = new byte[1024 * 8];
                    int currentLength = 0;
                    while (true) {
                        int num = inputStream.read(buf);
                        currentLength += num;
                        // 计算进度条位置
                        int progress = (int) ((currentLength / (float) length) * 100);
                        if (progress > oldProgress) {
                            oldProgress = progress;
                        }
                        if (num <= 0) {
                            break;
                        }
                        fos.write(buf, 0, num);
                        fos.flush();
                    }
                    fos.flush();
                    fos.close();
                    inputStream.close();
                } catch (Exception e) {
                    Log.i("updateException", e.toString());
                }
            }
        }).start();
    }
}
